package com.watson.redis;

import com.watson.Application;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @program: mytest
 * @description: redis tool
 * @author: zhangpeng348@jd.com
 * @date: 2018-12-14 14:48
 **/
public class RedisTool {

    public static final String pfKey = "test3";
    public static final int pfNum = 400;

    public static void main(String[] args) {
        RedisTool redisTool = new RedisTool();
        redisTool.testPfcount();

    }

    public void testPfAdd() {
        Jedis jedis = new Jedis();
        int startNum = 500000;
        Set<String> uidList = Application.genUid(startNum, pfNum);
        for (String s : uidList) {
            byte[] bytes = DigestUtils.md5Digest(s.getBytes());
            jedis.pfadd(pfKey.getBytes(), bytes);
        }

        long pfcount = jedis.pfcount(pfKey);
        jedis.del(pfKey);
        System.out.println(pfcount);
        System.out.println(Math.abs(pfNum - pfcount)/(double)pfNum);

    }

    public void testPfcount() {
        try {

            Jedis jedis = new Jedis();
            int startNum = 50;
            Set<String> uidList = Application.genUid(startNum, pfNum);
            int i = 0;
            List<String> md5List = new ArrayList<>();
            for (String s : uidList) {
                i++;
                String md5key = DigestUtils.md5DigestAsHex(s.getBytes());
                md5List.add(md5key);
                Set<String> addList = Application.genUid(startNum + pfNum * 100 * i / 2, pfNum*100);
                for (String s1 : addList) {
                    jedis.pfadd(md5key, s1);
                }
            }

            long st1 = System.currentTimeMillis();
            String[] keys = md5List.toArray(new String[0]);
            long st2 = System.currentTimeMillis();
            System.out.println("time1: " + String.valueOf(st2 - st1));

            long pfcount = jedis.pfcount(keys);
            long sum = 0;
            for (String key : keys) {
                sum += jedis.pfcount(key);
            }
            System.out.println("sum: " + sum);
            long st3 = System.currentTimeMillis();
            System.out.println("time2: " + String.valueOf(st3 - st2) + "count: " +  String.valueOf(pfcount));
            jedis.del(keys);
            System.out.println("rate: " + String.valueOf(Math.abs(pfNum*100*pfNum/2 - pfcount)/(double)(pfNum*100*pfNum/2)));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
